const productApi = require('../../api/product')
const balanceApi = require('../../api/balance')

Page({
  data: {
    productId: null,
    product: null,
    loading: true,
    purchasing: false,
    quantity: 1,
    userBalance: 0,
    userBalanceText: '0.00',
    showQuantityModal: false,
    totalPrice: '0.00',
    finalTotalPrice: '0.00',
    totalSavedAmount: '0.00',
    balanceStatus: 'sufficient',
    balanceStatusText: '（余额充足）'
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        productId: parseInt(options.id)
      })
      this.loadProductDetail()
      this.loadUserBalance()
    } else {
      wx.showToast({
        title: '商品ID不存在',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  /**
   * 加载商品详情
   */
  async loadProductDetail() {
    try {
      this.setData({ loading: true })
      
      const product = await productApi.getProductDetail(this.data.productId)
      
      if (product) {
        this.setData({
          product: product,
          loading: false
        })
        
        // 设置页面标题
        wx.setNavigationBarTitle({
          title: product.productName || '商品详情'
        })
        
        // 更新计算属性
        this.updateCalculatedData()
      } else {
        wx.showToast({
          title: '商品不存在',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    } catch (error) {
      console.error('加载商品详情失败:', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  /**
   * 加载用户余额
   */
  async loadUserBalance() {
    try {
      const balance = await balanceApi.getBalance()
      if (balance && balance.balance !== undefined) {
        this.setData({
          userBalance: balance.balance
        })
        this.updateCalculatedData()
      }
    } catch (error) {
      console.error('获取用户余额失败:', error)
    }
  },

  /**
   * 获取会员等级样式类
   */
  getMemberLevelClass(memberLevel) {
    switch (memberLevel) {
      case 'VIP1':
        return 'vip1'
      case 'VIP2':
        return 'vip2'
      case 'VIP3':
        return 'vip3'
      default:
        return 'normal'
    }
  },

  /**
   * 更新计算属性
   */
  updateCalculatedData() {
    const { product, quantity, userBalance } = this.data
    
    // 格式化用户余额
    const userBalanceText = userBalance.toFixed(2)
    
    if (!product) {
      this.setData({ userBalanceText })
      return
    }
    
    // 计算原始总价
    const totalPrice = (product.sellingPrice * quantity).toFixed(2)
    
    // 计算会员折扣后的总价
    let finalTotalPrice = totalPrice
    let totalSavedAmount = '0.00'
    
    if (product.hasMemberDiscount && product.memberDiscountPrice) {
      finalTotalPrice = (product.memberDiscountPrice * quantity).toFixed(2)
      totalSavedAmount = (product.savedAmount * quantity).toFixed(2)
    }
    
    // 计算余额状态（基于会员折扣价）
    const totalAmount = parseFloat(finalTotalPrice)
    const balanceStatus = userBalance >= totalAmount ? 'sufficient' : 'insufficient'
    const balanceStatusText = userBalance >= totalAmount ? '（余额充足）' : '（余额不足）'
    
    this.setData({
      userBalanceText,
      totalPrice,
      finalTotalPrice,
      totalSavedAmount,
      balanceStatus,
      balanceStatusText
    })
  },

  /**
   * 预览商品图片
   */
  onPreviewImage() {
    if (this.data.product && this.data.product.image) {
      wx.previewImage({
        urls: [this.data.product.image],
        current: this.data.product.image
      })
    }
  },

  /**
   * 显示购买数量选择弹窗
   */
  showQuantityModal() {
    const { product } = this.data
    
    if (!product) {
      wx.showToast({
        title: '商品信息加载中',
        icon: 'none'
      })
      return
    }

    if (product.status !== 1) {
      wx.showToast({
        title: '商品已下架',
        icon: 'none'
      })
      return
    }

    if (product.currentStock <= 0) {
      wx.showToast({
        title: '商品缺货',
        icon: 'none'
      })
      return
    }

    this.setData({
      showQuantityModal: true,
      quantity: 1
    })
    this.updateCalculatedData()
  },

  /**
   * 隐藏购买数量选择弹窗
   */
  hideQuantityModal() {
    this.setData({
      showQuantityModal: false
    })
  },

  /**
   * 减少数量
   */
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      })
      this.updateCalculatedData()
    }
  },

  /**
   * 增加数量
   */
  increaseQuantity() {
    const { product, quantity } = this.data
    if (quantity < product.currentStock) {
      this.setData({
        quantity: quantity + 1
      })
      this.updateCalculatedData()
    } else {
      wx.showToast({
        title: '超出库存数量',
        icon: 'none'
      })
    }
  },

  /**
   * 输入数量
   */
  onQuantityInput(e) {
    const value = parseInt(e.detail.value) || 1
    const { product } = this.data
    
    if (value < 1) {
      this.setData({ quantity: 1 })
    } else if (value > product.currentStock) {
      this.setData({ quantity: product.currentStock })
      wx.showToast({
        title: '超出库存数量',
        icon: 'none'
      })
    } else {
      this.setData({ quantity: value })
    }
    this.updateCalculatedData()
  },

  /**
   * 确认购买
   */
  async confirmPurchase() {
    const { product, quantity, userBalance } = this.data
    
    if (this.data.purchasing) return
    
    // 计算总价
    const totalAmount = product.sellingPrice * quantity
    
    // 检查余额
    if (userBalance < totalAmount) {
      wx.showModal({
        title: '余额不足',
        content: `购买需要 ¥${totalAmount.toFixed(2)}，当前余额 ¥${userBalance.toFixed(2)}，是否前往充值？`,
        confirmText: '去充值',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/recharge/recharge'
            })
          }
        }
      })
      return
    }

    // 确认购买
    wx.showModal({
      title: '确认购买',
      content: `购买 ${product.productName} × ${quantity}，总计 ¥${totalAmount.toFixed(2)}`,
      confirmText: '确认购买',
      success: async (res) => {
        if (res.confirm) {
          await this.executePurchase()
        }
      }
    })
  },

  /**
   * 执行购买
   */
  async executePurchase() {
    const { product, quantity } = this.data
    
    try {
      this.setData({ purchasing: true })
      
      const purchaseData = {
        productId: product.id,
        purchaseQuantity: quantity,
        remark: `小程序购买商品：${product.productName}`
      }
      
      await productApi.purchaseProduct(purchaseData)
      
      wx.showToast({
        title: '购买成功',
        icon: 'success'
      })
      
      // 隐藏弹窗
      this.hideQuantityModal()
      
      // 刷新商品信息和用户余额
      this.loadProductDetail()
      this.loadUserBalance()
      
      // 延迟跳转到购买记录页面
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/purchase-records/purchase-records'
        })
      }, 1500)
      
    } catch (error) {
      console.error('购买失败:', error)
      wx.showToast({
        title: error.message || '购买失败',
        icon: 'none'
      })
    } finally {
      this.setData({ purchasing: false })
    }
  },

  /**
   * 查看购买记录
   */
  viewPurchaseRecords() {
    wx.navigateTo({
      url: '/pages/purchase-records/purchase-records'
    })
  },

  /**
   * 分享商品
   */
  onShareAppMessage() {
    const { product } = this.data
    if (product) {
      return {
        title: `推荐商品：${product.productName}`,
        path: `/pages/product-detail/product-detail?id=${product.id}`,
        imageUrl: product.image
      }
    }
    return {}
  }
}) 